const express = require('express')
// 二. 实例化router对象
const router = express.Router()
const tools = require('../routes/upload')
const { getAll, getById, exec } = require('../db/index')
var bcrypt = require('bcryptjs')
const jwt = require('jsonwebtoken')
const config = require('./config.js')

router.post('/postuser', async (req, res) => {
  // 1.解析请求数据
  let { username, password, ismanager = 0, avatar = '' } = req.body
  password = bcrypt.hashSync(password, 10)
  // 2.编写sql语句
  let sql = `insert into users (username, password, ismanager, avatar) values ('${username}', '${password}', '${ismanager}', '${avatar}' )`
  // 3.执行sql语句
  const data = await exec(sql)
  const user = { username, ismanager, password: '' }
  const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: '2h' })
  res.send({
    code: 0,
    message: '添加用户成功',
    data: data,
    token: 'Bearer ' + tokenStr
  })
})

router.get('/', async (req, res) => {
  // 解析请求参数
  var { page, size } = req.query
  var sql = `select count(*) as total from users`
  let { total } = await getById(sql) // { total: 9 }
  // 偏移量 = (page -1) * size
  var offset = (page - 1) * size
  // 操作数据库
  sql = `select id, username,password,ismanager,avatar from users order by id desc limit ${offset}, ${size}`
  var data = await getAll(sql)
  if (data.length == 0) {
    page = page - 1
    offset = (page - 1) * size
    sql = `select id, username,password,ismanager,avatar from users order by id desc limit ${offset}, ${size}`
    data = await getAll(sql)
  }
  res.send({
    code: 0,
    message: '获取所有用户成功',
    result: {
      total,
      data
    },
    page: page
  })
})
router.get('/search/user', async (req, res) => {
  // 操作数据库
  const { page, size, searchMsg } = req.query
  let offset = (page - 1) * size
  let sql = `SELECT * from users WHERE username LIKE '%${searchMsg}%' limit ${offset},${size}`
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '查询用户成功',
    result: {
      data: data
    }
  })
})
router.get('/username', async (req, res) => {
  // 操作数据库
  const { username } = req.query
  let sql = `SELECT username from users WHERE username = '${username}' `
  const data = await getAll(sql)
  res.send({
    code: 0,
    message: '获取用户名成功',
    result: {
      data: data
    }
  })
})
router.get('/user/password', async (req, res) => {
  // 操作数据库
  let { username, password } = req.query
  let sql = `select * from users where username='${username}'`
  const userinfo = await getById(sql)
  const compareResult = bcrypt.compareSync(password, userinfo.password)
  if (compareResult) {
    const user = { ...userinfo, password: '' }
    const tokenStr = jwt.sign(user, config.jwtSecretKey, { expiresIn: '2h' })
    res.send({
      code: 0,
      message: '登录成功',
      token: 'Bearer ' + tokenStr,
      ismanager: userinfo.ismanager
    })
  } else {
    res.send({
      code: 1,
      message: '密码错误'
    })
  }
})
router.get('/:id', async (req, res) => {
  const { id } = req.params

  let sql = `select * from users where id=${id}`
  const data = await getById(sql)

  res.send({
    code: 0,
    message: '获取单个用户成功',
    result: data
  })
})

// PUT /users/id {username: 'new', password: 'new'}
router.put('/:id', async (req, res) => {
  const { id } = req.params
  let { username, password, avatar } = req.body
  password = bcrypt.hashSync(password, 10)
  let sql = `update users set username='${username}', password='${password}',avatar='${avatar}' where id=${id}`
  await exec(sql)
  res.send({
    code: 0,
    message: '修改成功',
    result: {
      id,
      username,
      password,
      avatar
    }
  })
})

// Delete /users/:id
router.delete('/:id', async (req, res) => {
  const { id } = req.params

  let sql = `delete from users where id=${id}`
  await exec(sql)

  res.send({
    code: 0,
    message: '删除成功',
    result: ''
  })
})
router.post('/upload', tools.upload().single('file'), (req, res) => {
  //single为multer对象的一个api
  //array为多文件处理
  res.send({
    // 给前端返回的数据
    file: req.file,
    path: `http://localhost:3000/images/${req.file.filename}` //返回url地址
  })
})
// 四. 导出router对象

module.exports = router
